/* $Id: os_core_unix.c 3999 2012-03-30 07:10:13Z bennylp $ */
/* 
 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
 */
/*
 * Contributors:
 * - Thanks for Zetron, Inc. (Phil Torre, ptorre@zetron.com) for donating
 *   the RTEMS port.
 */
#ifndef _GNU_SOURCE
#   define _GNU_SOURCE
#endif

#if 0
#include <dpl/os.h>
#include <dpl/assert.h>
#include <dpl/pool.h>
#include <dpl/log.h>
#include <dpl/rand.h>
#include <dpl/string.h>
#include <dpl/guid.h>
#include <dpl/except.h>
#include <dpl/errno.h>
#endif
#include <unistd.h>	    // getpid()
#include <errno.h>	    // errno

#include <pthread.h>
#include <dpl/os.h>
#include <dpl/config.h>


//#include "log.h"

D_LOG_DOMAIN(os_core_unix,"this is os core ");




#if defined(DPL_HAS_SEMAPHORE_H) && DPL_HAS_SEMAPHORE_H != 0
#  include <semaphore.h>
#endif



#define THIS_FILE   "os_core_unix.c"

#define SIGNATURE1  0xDEAFBEEF
#define SIGNATURE2  0xDEADC0DE

struct dpl_thread_t
{
    char	    obj_name[DPL_MAX_OBJ_NAME];
    pthread_t	    thread;
    dpl_thread_proc *proc;
    void	   *arg;
    dpl_uint32_t	    signature1;
    dpl_uint32_t	    signature2;

    dpl_mutex_t	   *suspended_mutex;

#if defined(DPL_OS_HAS_CHECK_STACK) && DPL_OS_HAS_CHECK_STACK!=0
    dpl_uint32_t	    stk_size;
    dpl_uint32_t	    stk_max_usage;
    char	   *stk_start;
    const char	   *caller_file;
    int		    caller_line;
#endif
};

struct dpl_atomic_t
{
    dpl_mutex_t	       *mutex;
    dpl_atomic_value_t	value;
};

struct dpl_mutex_t
{
    pthread_mutex_t     mutex;
    char		obj_name[DPL_MAX_OBJ_NAME];
#if DPL_DEBUG
    int		        nesting_level;
    dpl_thread_t	       *owner;
    char		owner_name[DPL_MAX_OBJ_NAME];
#endif
};

#if defined(DPL_HAS_SEMAPHORE) && DPL_HAS_SEMAPHORE != 0
struct dpl_sem_t
{
    sem_t	       *sem;
    char		obj_name[DPL_MAX_OBJ_NAME];
};
#endif /* DPL_HAS_SEMAPHORE */

#if defined(DPL_HAS_EVENT_OBJ) && DPL_HAS_EVENT_OBJ != 0
struct dpl_event_t
{
    char		obj_name[DPL_MAX_OBJ_NAME];
};
#endif	/* DPL_HAS_EVENT_OBJ */


/*
 * Flag and reference counter for DPLLIB instance.
 */
static int initialized;

#if DPL_HAS_THREADS
    static dpl_thread_t main_thread;
    static long thread_tls_id;
    static dpl_mutex_t critical_section;
#else
#   define MAX_THREADS 32
    static int tls_flag[MAX_THREADS];
    static void *tls[MAX_THREADS];
#endif

static unsigned atexit_count;
static void (*atexit_func[32])(void);

static dpl_status_t init_mutex(dpl_mutex_t *mutex, const char *name, int type);

/*
 * dpl_init(void).
 * Init DPLLIB!
 */
dpl_status_t dpl_init(void)
{
    char dummy_guid[DPL_GUID_MAX_LENGTH];
    dpl_str_t guid;
    dpl_status_t rc;

    /* Check if DPLLIB have been initialized */
    if (initialized) {
	++initialized;
	return DPL_SUCCESS;
    }

#if DPL_HAS_THREADS
    /* Init this thread's TLS. */
    if ((rc=dpl_thread_init()) != 0) {
	return rc;
    }

    /* Critical section. */
    if ((rc=init_mutex(&critical_section, "critsec", DPL_MUTEX_RECURSE)) != 0)
	return rc;

#endif

    /* Init logging */
    //dpl_log_init();


#if 0
    /* Initialize exception ID for the pool. 
     * Must do so after critical section is configured.
     */
    rc = dpl_exception_id_alloc("DPLLIB/No memory", &DPL_NO_MEMORY_EXCEPTION);
    if (rc != DPL_SUCCESS)
        return rc;
#endif  
    /* Init random seed. */
    /* Or probably not. Let application in charge of this */
    /* dpl_srand( clock() ); */

#if 0
    /* Startup GUID. */
    guid.ptr = dummy_guid;
    dpl_generate_unique_string( &guid );
#endif
    /* Startup timestamp */
#if defined(DPL_HAS_HIGH_RES_TIMER) && DPL_HAS_HIGH_RES_TIMER != 0
    {
	dpl_timestamp dummy_ts;
	if ((rc=dpl_get_timestamp(&dummy_ts)) != 0) {
	    return rc;
	}
    }
#endif   

    /* Flag DPLLIB as initialized */
    ++initialized;
    dpl_assert(initialized == 1);


    dpl_d("%s","1.0.0");

    return DPL_SUCCESS;
}

/*
 * dpl_atexit()
 */
dpl_status_t dpl_atexit(void (*func)(void))
{
    if (atexit_count >= DPL_ARRAY_SIZE(atexit_func))
	//return DPL_ETOOMANY;
	return DPL_FALSE;

    atexit_func[atexit_count++] = func;
    return DPL_FALSE;
}

/*
 * dpl_shutdown(void)
 */
void dpl_shutdown()
{
    int i;

    /* Only perform shutdown operation when 'initialized' reaches zero */
    dpl_assert(initialized > 0);
    if (--initialized != 0)
	return;

    /* Call atexit() functions */
    for (i=atexit_count-1; i>=0; --i) {
	(*atexit_func[i])();
    }
    atexit_count = 0;


#if 0
    /* Free exception ID */
    if (DPL_NO_MEMORY_EXCEPTION != -1) {
	dpl_exception_id_free(DPL_NO_MEMORY_EXCEPTION);
	DPL_NO_MEMORY_EXCEPTION = -1;
    }
#endif

#if DPL_HAS_THREADS
    /* Destroy DPLLIB critical section */
    dpl_mutex_destroy(&critical_section);

    /* Free DPLLIB TLS */
    if (thread_tls_id != -1) {
	dpl_thread_local_free(thread_tls_id);
	thread_tls_id = -1;
    }

    /* Ticket #1132: Assertion when (re)starting DPLLIB on different thread */
    bzero(&main_thread, sizeof(main_thread));
#endif

    /* Clear static variables */
    //dpl_errno_clear_handlers();
}


/*
 * dpl_getpid(void)
 */
dpl_uint32_t dpl_getpid(void)
{
    DPL_CHECK_STACK();
    return getpid();
}

/*
 * Check if this thread has been registered to DPLLIB.
 */
dpl_bool_t dpl_thread_is_registered(void)
{
#if DPL_HAS_THREADS
    return dpl_thread_local_get(thread_tls_id) != 0;
#else
    dpl_assert("dpl_thread_is_registered() called in non-threading mode!");
    return DPL_TRUE;
#endif
}


/*
 * Get thread priority value for the thread.
 */
int dpl_thread_get_prio(dpl_thread_t *thread)
{
#if DPL_HAS_THREADS
    struct sched_param param;
    int policy;
    int rc;

    rc = pthread_getschedparam (thread->thread, &policy, &param);
    if (rc != 0)
	return -1;

    return param.sched_priority;
#else
    DPL_UNUSED_ARG(thread);
    return 1;
#endif
}


/*
 * Set the thread priority.
 */
dpl_status_t dpl_thread_set_prio(dpl_thread_t *thread,  int prio)
{
#if DPL_HAS_THREADS
    struct sched_param param;
    int policy;
    int rc;

    rc = pthread_getschedparam (thread->thread, &policy, &param);
    if (rc != 0)
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;

    param.sched_priority = prio;

    rc = pthread_setschedparam(thread->thread, policy, &param);
    if (rc != 0)
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;

    return DPL_SUCCESS;
#else
    DPL_UNUSED_ARG(thread);
    DPL_UNUSED_ARG(prio);
    dpl_assert("dpl_thread_set_prio() called in non-threading mode!");
    return 1;
#endif
}


/*
 * Get the lowest priority value available on this system.
 */
int dpl_thread_get_prio_min(dpl_thread_t *thread)
{
    struct sched_param param;
    int policy;
    int rc;

    rc = pthread_getschedparam(thread->thread, &policy, &param);
    if (rc != 0)
	return -1;

#if defined(_POSIX_PRIORITY_SCHEDULING)
    return sched_get_priority_min(policy);
#elif defined __OpenBSD__
    /* Thread prio min/max are declared in OpenBSD private hdr */
    return 0;
#else
    dpl_assert("dpl_thread_get_prio_min() not supported!");
    return 0;
#endif
}


/*
 * Get the highest priority value available on this system.
 */
int dpl_thread_get_prio_max(dpl_thread_t *thread)
{
    struct sched_param param;
    int policy;
    int rc;

    rc = pthread_getschedparam(thread->thread, &policy, &param);
    if (rc != 0)
	return -1;

#if defined(_POSIX_PRIORITY_SCHEDULING)
    return sched_get_priority_max(policy);
#elif defined __OpenBSD__
    /* Thread prio min/max are declared in OpenBSD private hdr */
    return 31;
#else
    dpl_assert("dpl_thread_get_prio_max() not supported!");
    return 0;
#endif
}


/*
 * Get native thread handle
 */
void* dpl_thread_get_os_handle(dpl_thread_t *thread) 
{
    //DPL_ASSERT_RETURN(thread, NULL);

#if DPL_HAS_THREADS
    return &thread->thread;
#else
    dpl_assert("dpl_thread_is_registered() called in non-threading mode!");
    return NULL;
#endif
}

/*
 * dpl_thread_register(..)
 */
dpl_status_t dpl_thread_register ( const char *cstr_thread_name,
					 dpl_thread_desc desc,
					 dpl_thread_t **ptr_thread)
{
#if DPL_HAS_THREADS
    char stack_ptr;
    dpl_status_t rc;
    dpl_thread_t *thread = (dpl_thread_t *)desc;
    //dpl_str_t thread_name = dpl_str((char*)cstr_thread_name);
    char * thread_name = (char*)cstr_thread_name;
    /* Size sanity check. */
    if (sizeof(dpl_thread_desc) < sizeof(dpl_thread_t)) {
	dpl_assert(!"Not enough dpl_thread_desc size!");
	return DPL_FALSE;
    }

    /* Warn if this thread has been registered before */
    if (dpl_thread_local_get (thread_tls_id) != 0) {
	// 2006-02-26 bennylp:
	//  This wouldn't work in all cases!.
	//  If thread is created by external module (e.g. sound thread),
	//  thread may be reused while the pool used for the thread descriptor
	//  has been deleted by application.
	//*thread_ptr = (dpl_thread_t*)dpl_thread_local_get (thread_tls_id);
        //return DPL_SUCCESS;
    
        dpl_d("Info: possibly re-registering existing ");
    }

    /* On the other hand, also warn if the thread descriptor buffer seem to
     * have been used to register other threads.
     */
    dpl_assert(thread->signature1 != SIGNATURE1 ||
	      thread->signature2 != SIGNATURE2 ||
	      (thread->thread == pthread_self()));

    /* Initialize and set the thread entry. */
    bzero(desc, sizeof(struct dpl_thread_t));
    thread->thread = pthread_self();
    thread->signature1 = SIGNATURE1;
    thread->signature2 = SIGNATURE2;

    if(cstr_thread_name && strlen(thread_name) < sizeof(thread->obj_name)-1)
	snprintf(thread->obj_name, sizeof(thread->obj_name), 
			 cstr_thread_name, thread->thread);
    else
	snprintf(thread->obj_name, sizeof(thread->obj_name), 
			 "thr%p", (void*)thread->thread);
    
    rc = dpl_thread_local_set(thread_tls_id, thread);
    if (rc != DPL_SUCCESS) {
	bzero(desc, sizeof(struct dpl_thread_t));
	return rc;
    }

#if defined(DPL_OS_HAS_CHECK_STACK) && DPL_OS_HAS_CHECK_STACK!=0
    thread->stk_start = &stack_ptr;
    thread->stk_size = 0xFFFFFFFFUL;
    thread->stk_max_usage = 0;
#else
    stack_ptr = '\0';
#endif

    *ptr_thread = thread;
    
    return DPL_SUCCESS;
#else
    dpl_thread_t *thread = (dpl_thread_t*)desc;
    *ptr_thread = thread;
    return DPL_SUCCESS;
#endif
}


/*
 * dpl_thread_init(void)
 */
dpl_status_t dpl_thread_init(void)
{
#if DPL_HAS_THREADS
    dpl_status_t rc;
    dpl_thread_t *dummy;

    rc = dpl_thread_local_alloc(&thread_tls_id );
    if (rc != DPL_SUCCESS) {
        dpl_e("dpl_thread_local_alloc err!");
	return rc;
    }
    return dpl_thread_register("thr%p", (long*)&main_thread, &dummy);
#else
    //DPL_LOG(2,(THIS_FILE, "Thread init error. Threading is not enabled!"));
    return DPL_EINVALIDOP;
#endif
}


#if DPL_HAS_THREADS
/*
 * thread_main()
 *
 * This is the main entry for all threads.
 */
 

static void *thread_main(void *param)
{
    dpl_thread_t *rec = (dpl_thread_t*)param;
    void *result;
    dpl_status_t rc;

#if defined(DPL_OS_HAS_CHECK_STACK) && DPL_OS_HAS_CHECK_STACK!=0
    rec->stk_start = (char*)&rec;
#endif

    /* Set current thread id. */
    rc = dpl_thread_local_set(thread_tls_id, rec);
    if (rc != DPL_SUCCESS) {
	dpl_assert(!"Thread TLS ID is not set (dpl_init() error?)");
    }

    /* Check if suspension is required. */
    if (rec->suspended_mutex) {
	dpl_mutex_lock(rec->suspended_mutex);
	dpl_mutex_unlock(rec->suspended_mutex);
    }

   
    dpl_v("Thread started");

    /* Call user's entry! */
    result = (void*)(long)(*rec->proc)(rec->arg);

    /* Done. */

    dpl_v("Thread quitting");

    return result;
}
#endif

/*
 * dpl_thread_create(...)
 */
dpl_status_t dpl_thread_create( dpl_pool_t *pool, 
				      const char *thread_name,
				      dpl_thread_proc *proc, 
				      void *arg,
				      dpl_size_t stack_size, 
				      unsigned flags,
				      dpl_thread_t **ptr_thread)
{
    DPL_UNUSED_ARG(pool);
#if DPL_HAS_THREADS
    dpl_thread_t *rec;
    pthread_attr_t thread_attr;
    void *stack_addr;
    int rc;
    
    DPL_UNUSED_ARG(stack_addr);

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(pool && proc && ptr_thread, DPL_EINVAL);

    /* Create thread record and assign name for the thread */
    rec = (struct dpl_thread_t*) malloc( sizeof(dpl_thread_t));
    //DPL_ASSERT_RETURN(rec, DPL_ENOMEM);
    
    /* Set name. */
    if (!thread_name) 
	thread_name = "thr%p";
    
    if (strchr(thread_name, '%')) {
	snprintf(rec->obj_name, DPL_MAX_OBJ_NAME, thread_name, rec);
    } else {
	strncpy(rec->obj_name, thread_name, DPL_MAX_OBJ_NAME);
	rec->obj_name[DPL_MAX_OBJ_NAME-1] = '\0';
    }

    /* Set default stack size */
    if (stack_size == 0)
	stack_size = 8192;//8k
	

#if defined(DPL_OS_HAS_CHECK_STACK) && DPL_OS_HAS_CHECK_STACK!=0
    rec->stk_size = stack_size;
    rec->stk_max_usage = 0;
#endif

    /* Emulate suspended thread with mutex. */
    if (flags & DPL_THREAD_SUSPENDED) {
	rc = dpl_mutex_create_simple(pool, NULL, &rec->suspended_mutex);
	if (rc != DPL_SUCCESS) {
	    return rc;
	}

	dpl_mutex_lock(rec->suspended_mutex);
    } else {
	dpl_assert(rec->suspended_mutex == NULL);
    }
    
    
    /* Init thread attributes */
    pthread_attr_init(&thread_attr);

#if defined(DPL_THREAD_SET_STACK_SIZE) && DPL_THREAD_SET_STACK_SIZE!=0
    /* Set thread's stack size */
    rc = pthread_attr_setstacksize(&thread_attr, stack_size);
    if (rc != 0)
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;
#endif	/* DPL_THREAD_SET_STACK_SIZE */


#if defined(DPL_THREAD_ALLOCATE_STACK) && DPL_THREAD_ALLOCATE_STACK!=0
    /* Allocate memory for the stack */
    stack_addr = dpl_pool_alloc(pool, stack_size);
//    DPL_ASSERT_RETURN(stack_addr, DPL_ENOMEM);

    rc = pthread_attr_setstackaddr(&thread_attr, stack_addr);
    if (rc != 0)
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;
#endif	/* DPL_THREAD_ALLOCATE_STACK */

    
    /* Create the thread. */
    rec->proc = proc;
    rec->arg = arg;
    rc = pthread_create( &rec->thread, &thread_attr, &thread_main, rec);
    if (rc != 0) {
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;
    }

    *ptr_thread = rec;

    //DPL_LOG(6, (rec->obj_name, "Thread created"));
    dpl_v("Thread created");
    return DPL_SUCCESS;
#else
    dpl_assert(!"Threading is disabled!");
    return DPL_EINVALIDOP;
#endif
}

/*
 * dpl_thread-get_name()
 */
const char* dpl_thread_get_name(dpl_thread_t *p)
{
#if DPL_HAS_THREADS
    dpl_thread_t *rec = (dpl_thread_t*)p;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(p, "");

    return rec->obj_name;
#else
    return "";
#endif
}

/*
 * dpl_thread_resume()
 */
dpl_status_t dpl_thread_resume(dpl_thread_t *p)
{
    dpl_status_t rc;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(p, DPL_EINVAL);

    rc = dpl_mutex_unlock(p->suspended_mutex);

    return rc;
}

/*
 * dpl_thread_this()
 */
dpl_thread_t* dpl_thread_this(void)
{
#if DPL_HAS_THREADS
    dpl_thread_t *rec = (dpl_thread_t*)dpl_thread_local_get(thread_tls_id);
    
    if (rec == NULL) {
	dpl_assert(!"Calling dpllib from unknown/external thread. You must "
		   "register external threads with dpl_thread_register() "
		   "before calling any dpllib functions.");
    }

    /*
     * MUST NOT check stack because this function is called
     * by DPL_CHECK_STACK() itself!!!
     *
     */

    return rec;
#else
    dpl_assert(!"Threading is not enabled!");
    return NULL;
#endif
}

/*
 * dpl_thread_join()
 */
dpl_status_t dpl_thread_join(dpl_thread_t *p)
{
#if DPL_HAS_THREADS
    dpl_thread_t *rec = (dpl_thread_t *)p;
    void *ret;
    int result;

    DPL_CHECK_STACK();

//    DPL_LOG(6, (dpl_thread_this()->obj_name, "Joining thread %s", p->obj_name));
    dpl_v("Joining thread %s", p->obj_name);
    result = pthread_join( rec->thread, &ret);

    if (result == 0)
	return DPL_SUCCESS;
    else {
	/* Calling pthread_join() on a thread that no longer exists and 
	 * getting back ESRCH isn't an error (in this context). 
	 * Thanks Phil Torre <ptorre@zetron.com>.
	 */
	//return result==ESRCH ? DPL_SUCCESS : DPL_RETURN_OS_ERROR(result);
	return result==ESRCH ? DPL_SUCCESS : result;
    }
#else
    DPL_CHECK_STACK();
    dpl_assert(!"No multithreading support!");
    return DPL_EINVALIDOP;
#endif
}

/*
 * dpl_thread_destroy()
 */
dpl_status_t dpl_thread_destroy(dpl_thread_t *p)
{
    DPL_CHECK_STACK();

    /* Destroy mutex used to suspend thread */
    if (p->suspended_mutex) {
	dpl_mutex_destroy(p->suspended_mutex);
	p->suspended_mutex = NULL;
    }

    return DPL_SUCCESS;
}

/*
 * dpl_thread_sleep()
 */
dpl_status_t dpl_thread_sleep(unsigned msec)
{
/* TODO: should change this to something like DPL_OS_HAS_NANOSLEEP */
#if defined(DPL_RTEMS) && DPL_RTEMS!=0
    enum { NANOSEC_PER_MSEC = 1000000 };
    struct timespec req;

    DPL_CHECK_STACK();
    req.tv_sec = msec / 1000;
    req.tv_nsec = (msec % 1000) * NANOSEC_PER_MSEC;

    if (nanosleep(&req, NULL) == 0)
	return DPL_SUCCESS;

    //return DPL_RETURN_OS_ERROR(dpl_get_native_os_error());
    return dpl_get_native_os_error();
#else
    DPL_CHECK_STACK();

   // dpl_set_os_error(0);

    usleep(msec * 1000);

    /* MacOS X (reported on 10.5) seems to always set errno to ETIMEDOUT.
     * It does so because usleep() is declared to return int, and we're
     * supposed to check for errno only when usleep() returns non-zero. 
     * Unfortunately, usleep() is declared to return void in other platforms
     * so it's not possible to always check for the return value (unless 
     * we add a detection routine in autoconf).
     *
     * As a workaround, here we check if ETIMEDOUT is returned and
     * return successfully if it is.
     */
    //if (dpl_get_native_os_error() == ETIMEDOUT)
	//return DPL_SUCCESS;

    //return dpl_get_os_error();
    return DPL_SUCCESS;
#endif	/* DPL_RTEMS */
}

#if defined(DPL_OS_HAS_CHECK_STACK) && DPL_OS_HAS_CHECK_STACK!=0
/*
 * dpl_thread_check_stack()
 * Implementation for DPL_CHECK_STACK()
 */
void dpl_thread_check_stack(const char *file, int line)
{
    char stk_ptr;
    dpl_uint32_t usage;
    dpl_thread_t *thread = dpl_thread_this();

    /* Calculate current usage. */
    usage = (&stk_ptr > thread->stk_start) ? &stk_ptr - thread->stk_start :
		thread->stk_start - &stk_ptr;

    /* Assert if stack usage is dangerously high. */
    dpl_assert("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128));

    /* Keep statistic. */
    if (usage > thread->stk_max_usage) {
	thread->stk_max_usage = usage;
	thread->caller_file = file;
	thread->caller_line = line;
    }
}

/*
 * dpl_thread_get_stack_max_usage()
 */
dpl_uint32_t dpl_thread_get_stack_max_usage(dpl_thread_t *thread)
{
    return thread->stk_max_usage;
}

/*
 * dpl_thread_get_stack_info()
 */
dpl_status_t dpl_thread_get_stack_info( dpl_thread_t *thread,
					      const char **file,
					      int *line )
{
    dpl_assert(thread);

    *file = thread->caller_file;
    *line = thread->caller_line;
    return 0;
}

#endif	/* DPL_OS_HAS_CHECK_STACK */

///////////////////////////////////////////////////////////////////////////////
/*
 * dpl_atomic_create()
 */
dpl_status_t dpl_atomic_create( dpl_pool_t *pool, 
				      dpl_atomic_value_t initial,
				      dpl_atomic_t **ptr_atomic)
{
    DPL_UNUSED_ARG(pool);
    dpl_status_t rc;
    dpl_atomic_t *atomic_var;

    //atomic_var = DPL_POOL_ZALLOC_T(pool, dpl_atomic_t);
    atomic_var = malloc(sizeof( dpl_atomic_t));

//    DPL_ASSERT_RETURN(atomic_var, DPL_ENOMEM);
    
#if DPL_HAS_THREADS
    rc = dpl_mutex_create(pool, "atm%p", DPL_MUTEX_SIMPLE, &atomic_var->mutex);
    if (rc != DPL_SUCCESS)
	return rc;
#endif
    atomic_var->value = initial;

    *ptr_atomic = atomic_var;
    return DPL_SUCCESS;
}

/*
 * dpl_atomic_destroy()
 */
dpl_status_t dpl_atomic_destroy( dpl_atomic_t *atomic_var )
{
    //DPL_ASSERT_RETURN(atomic_var, DPL_EINVAL);
#if DPL_HAS_THREADS
    return dpl_mutex_destroy( atomic_var->mutex );
#else
    return 0;
#endif
}

/*
 * dpl_atomic_set()
 */
void dpl_atomic_set(dpl_atomic_t *atomic_var, dpl_atomic_value_t value)
{
    DPL_CHECK_STACK();

#if DPL_HAS_THREADS
    dpl_mutex_lock( atomic_var->mutex );
#endif
    atomic_var->value = value;
#if DPL_HAS_THREADS
    dpl_mutex_unlock( atomic_var->mutex);
#endif 
}

/*
 * dpl_atomic_get()
 */
dpl_atomic_value_t dpl_atomic_get(dpl_atomic_t *atomic_var)
{
    dpl_atomic_value_t oldval;
    
    DPL_CHECK_STACK();

#if DPL_HAS_THREADS
    dpl_mutex_lock( atomic_var->mutex );
#endif
    oldval = atomic_var->value;
#if DPL_HAS_THREADS
    dpl_mutex_unlock( atomic_var->mutex);
#endif
    return oldval;
}

/*
 * dpl_atomic_inc_and_get()
 */
dpl_atomic_value_t dpl_atomic_inc_and_get(dpl_atomic_t *atomic_var)
{
    dpl_atomic_value_t new_value;

    DPL_CHECK_STACK();

#if DPL_HAS_THREADS
    dpl_mutex_lock( atomic_var->mutex );
#endif
    new_value = ++atomic_var->value;
#if DPL_HAS_THREADS
    dpl_mutex_unlock( atomic_var->mutex);
#endif

    return new_value;
}
/*
 * dpl_atomic_inc()
 */
void dpl_atomic_inc(dpl_atomic_t *atomic_var)
{
    dpl_atomic_inc_and_get(atomic_var);
}

/*
 * dpl_atomic_dec_and_get()
 */
dpl_atomic_value_t dpl_atomic_dec_and_get(dpl_atomic_t *atomic_var)
{
    dpl_atomic_value_t new_value;

    DPL_CHECK_STACK();

#if DPL_HAS_THREADS
    dpl_mutex_lock( atomic_var->mutex );
#endif
    new_value = --atomic_var->value;
#if DPL_HAS_THREADS
    dpl_mutex_unlock( atomic_var->mutex);
#endif

    return new_value;
}

/*
 * dpl_atomic_dec()
 */
void dpl_atomic_dec(dpl_atomic_t *atomic_var)
{
    dpl_atomic_dec_and_get(atomic_var);
}

/*
 * dpl_atomic_add_and_get()
 */ 
dpl_atomic_value_t dpl_atomic_add_and_get( dpl_atomic_t *atomic_var, 
                                                 dpl_atomic_value_t value )
{
    dpl_atomic_value_t new_value;

#if DPL_HAS_THREADS
    dpl_mutex_lock(atomic_var->mutex);
#endif
    
    atomic_var->value += value;
    new_value = atomic_var->value;

#if DPL_HAS_THREADS
    dpl_mutex_unlock(atomic_var->mutex);
#endif

    return new_value;
}

/*
 * dpl_atomic_add()
 */ 
void dpl_atomic_add( dpl_atomic_t *atomic_var, 
                            dpl_atomic_value_t value )
{
    dpl_atomic_add_and_get(atomic_var, value);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * dpl_thread_local_alloc()
 */
dpl_status_t dpl_thread_local_alloc(long *p_index)
{
#if DPL_HAS_THREADS
    pthread_key_t key;
    int rc;

    //DPL_ASSERT_RETURN(p_index != NULL, DPL_EINVAL);

    dpl_assert( sizeof(pthread_key_t) <= sizeof(long));
    if ((rc=pthread_key_create(&key, NULL)) != 0)
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;

    *p_index = key;
    return DPL_SUCCESS;
#else
    int i;
    for (i=0; i<MAX_THREADS; ++i) {
	if (tls_flag[i] == 0)
	    break;
    }
    if (i == MAX_THREADS) 
	return DPL_ETOOMANY;
    
    tls_flag[i] = 1;
    tls[i] = NULL;

    *p_index = i;
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_thread_local_free()
 */
void dpl_thread_local_free(long index)
{
    DPL_CHECK_STACK();
#if DPL_HAS_THREADS
    pthread_key_delete(index);
#else
    tls_flag[index] = 0;
#endif
}

/*
 * dpl_thread_local_set()
 */
dpl_status_t dpl_thread_local_set(long index, void *value)
{
    //Can't check stack because this function is called in the
    //beginning before main thread is initialized.
    //DPL_CHECK_STACK();
#if DPL_HAS_THREADS
    int rc=pthread_setspecific(index, value);
   // return rc==0 ? DPL_SUCCESS : DPL_RETURN_OS_ERROR(rc);
    return rc==0 ? DPL_SUCCESS : rc;
#else
    dpl_assert(index >= 0 && index < MAX_THREADS);
    tls[index] = value;
    return DPL_SUCCESS;
#endif
}

void* dpl_thread_local_get(long index)
{
    //Can't check stack because this function is called
    //by DPL_CHECK_STACK() itself!!!
    //DPL_CHECK_STACK();
#if DPL_HAS_THREADS
    return pthread_getspecific(index);
#else
    dpl_assert(index >= 0 && index < MAX_THREADS);
    return tls[index];
#endif
}

///////////////////////////////////////////////////////////////////////////////
void dpl_enter_critical_section(void)
{
#if DPL_HAS_THREADS
    dpl_mutex_lock(&critical_section);
#endif
}

void dpl_leave_critical_section(void)
{
#if DPL_HAS_THREADS
    dpl_mutex_unlock(&critical_section);
#endif
}


///////////////////////////////////////////////////////////////////////////////
#if defined(DPL_LINUX) && DPL_LINUX!=0

int pthread_mutexattr_settype(pthread_mutexattr_t*,int);

#endif

static dpl_status_t init_mutex(dpl_mutex_t *mutex, const char *name, int type)
{
#if DPL_HAS_THREADS
    pthread_mutexattr_t attr;
    int rc;

    DPL_CHECK_STACK();

    rc = pthread_mutexattr_init(&attr);
    if (rc != 0)
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;

    if (type == DPL_MUTEX_SIMPLE) {
#if (defined(DPL_LINUX) && DPL_LINUX!=0) || \
    defined(DPL_HAS_PTHREAD_MUTEXATTR_SETTYPE)
	rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_FAST_NP);
#elif (defined(DPL_RTEMS) && DPL_RTEMS!=0) || \
       defined(DPL_PTHREAD_MUTEXATTR_T_HAS_RECURSIVE)
	/* Nothing to do, default is simple */
#else
	rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
#endif
    } else {
#if (defined(DPL_LINUX) && DPL_LINUX!=0) || \
     defined(DPL_HAS_PTHREAD_MUTEXATTR_SETTYPE)
	rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
#elif (defined(DPL_RTEMS) && DPL_RTEMS!=0) || \
       defined(DPL_PTHREAD_MUTEXATTR_T_HAS_RECURSIVE)
	// Phil Torre <ptorre@zetron.com>:
	// The RTEMS implementation of POSIX mutexes doesn't include 
	// pthread_mutexattr_settype(), so what follows is a hack
	// until I get RTEMS patched to support the set/get functions.
	//
	// More info:
	//   newlib's pthread also lacks pthread_mutexattr_settype(),
	//   but it seems to have mutexattr.recursive.
	DPL_TODO(FIX_RTEMS_RECURSIVE_MUTEX_TYPE)
	attr.recursive = 1;
#else
	rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
#endif
    }
    
    if (rc != 0) {
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;
    }

    rc = pthread_mutex_init(&mutex->mutex, &attr);
    if (rc != 0) {
	//return DPL_RETURN_OS_ERROR(rc);
	return rc;
    }
    
    rc = pthread_mutexattr_destroy(&attr);
    if (rc != 0) {
	//dpl_status_t status = DPL_RETURN_OS_ERROR(rc);
	dpl_status_t status = rc;
	pthread_mutex_destroy(&mutex->mutex);
	return status;
    }

#if DPL_DEBUG
    /* Set owner. */
    mutex->nesting_level = 0;
    mutex->owner = NULL;
#endif

    /* Set name. */
    if (!name) {
	name = "mtx%p";
    }
    if (strchr(name, '%')) {
	snprintf(mutex->obj_name, DPL_MAX_OBJ_NAME, name, mutex);
    } else {
	strncpy(mutex->obj_name, name, DPL_MAX_OBJ_NAME);
	mutex->obj_name[DPL_MAX_OBJ_NAME-1] = '\0';
    }

//    DPL_LOG(6, (mutex->obj_name, "Mutex created"));
    dpl_v("Mutex created");
    return DPL_SUCCESS;
#else /* DPL_HAS_THREADS */
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_mutex_create()
 */
dpl_status_t dpl_mutex_create(dpl_pool_t *pool, 
				    const char *name, 
				    int type,
				    dpl_mutex_t **ptr_mutex)
{
#if DPL_HAS_THREADS
    DPL_UNUSED_ARG(pool);
    dpl_status_t rc;
    dpl_mutex_t *mutex;

    //DPL_ASSERT_RETURN(pool && ptr_mutex, DPL_EINVAL);

    //mutex = DPL_POOL_ALLOC_T(pool, dpl_mutex_t);
    mutex = malloc(sizeof( dpl_mutex_t));
//    DPL_ASSERT_RETURN(mutex, DPL_ENOMEM);

    if ((rc=init_mutex(mutex, name, type)) != DPL_SUCCESS)
	return rc;
    
    *ptr_mutex = mutex;
    return DPL_SUCCESS;
#else /* DPL_HAS_THREADS */
    *ptr_mutex = (dpl_mutex_t*)1;
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_mutex_create_simple()
 */
dpl_status_t dpl_mutex_create_simple( dpl_pool_t *pool, 
                                            const char *name,
					    dpl_mutex_t **mutex )
{
    return dpl_mutex_create(pool, name, DPL_MUTEX_SIMPLE, mutex);
}

/*
 * dpl_mutex_create_recursive()
 */
dpl_status_t dpl_mutex_create_recursive( dpl_pool_t *pool,
					       const char *name,
					       dpl_mutex_t **mutex )
{
    return dpl_mutex_create(pool, name, DPL_MUTEX_RECURSE, mutex);
}

/*
 * dpl_mutex_lock()
 */
dpl_status_t dpl_mutex_lock(dpl_mutex_t *mutex)
{
#if DPL_HAS_THREADS
    
    dpl_status_t status;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(mutex, DPL_EINVAL);


    dpl_v("Mutex: thread %s is waiting", dpl_thread_this()->obj_name);
    status = pthread_mutex_lock( &mutex->mutex );


#if DPL_DEBUG
    if (status == DPL_SUCCESS) {
	mutex->owner = dpl_thread_this();
	dpl_ansi_strcpy(mutex->owner_name, mutex->owner->obj_name);
	++mutex->nesting_level;
    }
   
	dpl_v("Mutex acquired by thread %s (level=%d)",dpl_thread_this()->obj_name);
#else
   
	dpl_v("Mutex acquired by thread %s" ,dpl_thread_this()->obj_name);
	      
#endif

    if (status == 0)
	return DPL_SUCCESS;
    else
	//return DPL_RETURN_OS_ERROR(status);
	return status;
#else	/* DPL_HAS_THREADS */
    dpl_assert( mutex == (dpl_mutex_t*)1 );
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_mutex_unlock()
 */
dpl_status_t dpl_mutex_unlock(dpl_mutex_t *mutex)
{
#if DPL_HAS_THREADS
    dpl_status_t status;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(mutex, DPL_EINVAL);

#if DPL_DEBUG
    dpl_assert(mutex->owner == dpl_thread_this());
    if (--mutex->nesting_level == 0) {
	mutex->owner = NULL;
	mutex->owner_name[0] = '\0';
    }


	dpl_v("Mutex released by thread %s (level=%d)",dpl_thread_this()->obj_name,mutex->nesting_level);
#else

	dpl_v("Mutex released by thread %s",dpl_thread_this()->obj_name);
#endif

    status = pthread_mutex_unlock( &mutex->mutex );
    if (status == 0)
	return DPL_SUCCESS;
    else
	//return DPL_RETURN_OS_ERROR(status);
	return status;

#else /* DPL_HAS_THREADS */
    dpl_assert( mutex == (dpl_mutex_t*)1 );
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_mutex_trylock()
 */
dpl_status_t dpl_mutex_trylock(dpl_mutex_t *mutex)
{
#if DPL_HAS_THREADS
    int status;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(mutex, DPL_EINVAL);

  
    dpl_v("Mutex: thread %s is trying",dpl_thread_this()->obj_name);
    status = pthread_mutex_trylock( &mutex->mutex );

    if (status==0) {
#if DPL_DEBUG
	mutex->owner = dpl_thread_this();
	dpl_ansi_strcpy(mutex->owner_name, mutex->owner->obj_name);
	++mutex->nesting_level;

	
	dpl_v("Mutex acquired by thread %s (level=%d)", dpl_thread_this()->obj_name, mutex->nesting_level);
#else

	dpl_v("Mutex acquired by thread %s", dpl_thread_this()->obj_name);
#endif
    } else {
	
	dpl_v("Mutex: thread %s's trylock() failed",dpl_thread_this()->obj_name);
    }
    
    if (status==0)
	return DPL_SUCCESS;
    else
	//return DPL_RETURN_OS_ERROR(status);
	return status;
#else	/* DPL_HAS_THREADS */
    dpl_assert( mutex == (dpl_mutex_t*)1);
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_mutex_destroy()
 */
dpl_status_t dpl_mutex_destroy(dpl_mutex_t *mutex)
{
    enum { RETRY = 4 };
    int status = 0;
    unsigned retry;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(mutex, DPL_EINVAL);

#if DPL_HAS_THREADS
    
	dpl_v("Mutex destroyed by thread %s", dpl_thread_this()->obj_name);

    for (retry=0; retry<RETRY; ++retry) {
	status = pthread_mutex_destroy( &mutex->mutex );
	if (status == DPL_SUCCESS)
	    break;
	else if (retry<RETRY-1 && status == EBUSY)
	    pthread_mutex_unlock(&mutex->mutex);
    }

    if (status == 0)
	return DPL_SUCCESS;
    else {
	//return DPL_RETURN_OS_ERROR(status);
	return status;
    }
#else
    dpl_assert( mutex == (dpl_mutex_t*)1 );
    status = DPL_SUCCESS;
    return status;
#endif
}

#if DPL_DEBUG
dpl_bool_t dpl_mutex_is_locked(dpl_mutex_t *mutex)
{
#if DPL_HAS_THREADS
    return mutex->owner == dpl_thread_this();
#else
    return 1;
#endif
}
#endif

///////////////////////////////////////////////////////////////////////////////
/*
 * Include Read/Write mutex emulation for POSIX platforms that lack it (e.g.
 * RTEMS). Otherwise use POSIX rwlock.
 */
#if defined(DPL_EMULATE_RWMUTEX) && DPL_EMULATE_RWMUTEX!=0
    /* We need semaphore functionality to emulate rwmutex */
#   if !defined(DPL_HAS_SEMAPHORE) || DPL_HAS_SEMAPHORE==0
#	error "Semaphore support needs to be enabled to emulate rwmutex"
#   endif
#   include "os_rwmutex.c"
#else
struct dpl_rwmutex_t
{
    pthread_rwlock_t rwlock;
};

dpl_status_t dpl_rwmutex_create(dpl_pool_t *pool, const char *name,
				      dpl_rwmutex_t **p_mutex)
{
    DPL_UNUSED_ARG(pool);
    dpl_rwmutex_t *rwm;
    dpl_status_t status;

    DPL_UNUSED_ARG(name);
    
    //rwm = DPL_POOL_ALLOC_T(pool, dpl_rwmutex_t);
    rwm = malloc(sizeof(dpl_rwmutex_t));
//    DPL_ASSERT_RETURN(rwm, DPL_ENOMEM);

    status = pthread_rwlock_init(&rwm->rwlock, NULL);
    if (status != 0)
	//return DPL_RETURN_OS_ERROR(status);
	return status;

    *p_mutex = rwm;
    return DPL_SUCCESS;
}

/*
 * Lock the mutex for reading.
 *
 */
dpl_status_t dpl_rwmutex_lock_read(dpl_rwmutex_t *mutex)
{
    dpl_status_t status;

    status = pthread_rwlock_rdlock(&mutex->rwlock);
    if (status != 0)
	//return DPL_RETURN_OS_ERROR(status);
	return status;

    return DPL_SUCCESS;
}

/*
 * Lock the mutex for writing.
 *
 */
dpl_status_t dpl_rwmutex_lock_write(dpl_rwmutex_t *mutex)
{
    dpl_status_t status;

    status = pthread_rwlock_wrlock(&mutex->rwlock);
    if (status != 0)
	//return DPL_RETURN_OS_ERROR(status);
	return status;

    return DPL_SUCCESS;
}

/*
 * Release read lock.
 *
 */
dpl_status_t dpl_rwmutex_unlock_read(dpl_rwmutex_t *mutex)
{
    return dpl_rwmutex_unlock_write(mutex);
}

/*
 * Release write lock.
 *
 */
dpl_status_t dpl_rwmutex_unlock_write(dpl_rwmutex_t *mutex)
{
    dpl_status_t status;

    status = pthread_rwlock_unlock(&mutex->rwlock);
    if (status != 0)
	//return DPL_RETURN_OS_ERROR(status);
	return status;

    return DPL_SUCCESS;
}

/*
 * Destroy reader/writer mutex.
 *
 */
dpl_status_t dpl_rwmutex_destroy(dpl_rwmutex_t *mutex)
{
    dpl_status_t status;

    status = pthread_rwlock_destroy(&mutex->rwlock);
    if (status != 0)
	//return DPL_RETURN_OS_ERROR(status);
	return status;

    return DPL_SUCCESS;
}

#endif	/* DPL_EMULATE_RWMUTEX */


///////////////////////////////////////////////////////////////////////////////
#if defined(DPL_HAS_SEMAPHORE) && DPL_HAS_SEMAPHORE != 0

/*
 * dpl_sem_create()
 */
dpl_status_t dpl_sem_create( dpl_pool_t *pool, 
				   const char *name,
				   unsigned initial, 
				   unsigned max,
				   dpl_sem_t **ptr_sem)
{
#if DPL_HAS_THREADS
    dpl_sem_t *sem;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(pool != NULL && ptr_sem != NULL, DPL_EINVAL);

    sem = malloc(sizeof( *sem));
//    DPL_ASSERT_RETURN(sem, DPL_ENOMEM);

#if defined(DPL_DARWINOS) && DPL_DARWINOS!=0
    /* MacOS X doesn't support anonymous semaphore */
    {
	char sem_name[DPL_GUID_MAX_LENGTH+1];
	dpl_str_t nam;

	/* We should use SEM_NAME_LEN, but this doesn't seem to be 
	 * declared anywhere? The value here is just from trial and error
	 * to get the longest name supported.
	 */
#	define MAX_SEM_NAME_LEN	23

	/* Create a unique name for the semaphore. */
	if (DPL_GUID_STRING_LENGTH <= MAX_SEM_NAME_LEN) {
	    nam.ptr = sem_name;
	    dpl_generate_unique_string(&nam);
	    sem_name[nam.slen] = '\0';
	} else {
	    dpl_create_random_string(sem_name, MAX_SEM_NAME_LEN);
	    sem_name[MAX_SEM_NAME_LEN] = '\0';
	}

	/* Create semaphore */
	sem->sem = sem_open(sem_name, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR, 
			    initial);
	if (sem->sem == SEM_FAILED)
	    //return DPL_RETURN_OS_ERROR(dpl_get_native_os_error());
	    return dpl_get_native_os_error();

	/* And immediately release the name as we don't need it */
	sem_unlink(sem_name);
    }
#else
    sem->sem = malloc(sizeof( sem_t));
    if (sem_init( sem->sem, 0, initial) != 0) 
	//return DPL_RETURN_OS_ERROR(dpl_get_native_os_error());
	return -1;
#endif
    
    /* Set name. */
    if (!name) {
	name = "sem%p";
    }
    if (strchr(name, '%')) {
	snprintf(sem->obj_name, DPL_MAX_OBJ_NAME, name, sem);
    } else {
	strncpy(sem->obj_name, name, DPL_MAX_OBJ_NAME);
	sem->obj_name[DPL_MAX_OBJ_NAME-1] = '\0';
    }

   // DPL_LOG(6, (sem->obj_name, "Semaphore created"));
    dpl_v(sem->obj_name, "Semaphore created");

    *ptr_sem = sem;
    return DPL_SUCCESS;
#else
    *ptr_sem = (dpl_sem_t*)1;
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_sem_wait()
 */
dpl_status_t dpl_sem_wait(dpl_sem_t *sem)
{
#if DPL_HAS_THREADS
    int result;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(sem, DPL_EINVAL);

    
	dpl_v("Semaphore: thread %s is waiting",  dpl_thread_this()->obj_name);

    result = sem_wait( sem->sem );
    
    if (result == 0) {
	
	dpl_v("Semaphore acquired by thread %s",dpl_thread_this()->obj_name);
    } else {
	
	dpl_v("Semaphore: thread %s FAILED to acquire",dpl_thread_this()->obj_name);
    }

    if (result == 0)
	return DPL_SUCCESS;
    else
	//return DPL_RETURN_OS_ERROR(dpl_get_native_os_error());
	return -1;
#else
    dpl_assert( sem == (dpl_sem_t*) 1 );
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_sem_trywait()
 */
dpl_status_t dpl_sem_trywait(dpl_sem_t *sem)
{
#if DPL_HAS_THREADS
    int result;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(sem, DPL_EINVAL);

    result = sem_trywait( sem->sem );
    
    if (result == 0) {
	
	dpl_v("Semaphore acquired by thread %s", dpl_thread_this()->obj_name );
    } 
    if (result == 0)
	return DPL_SUCCESS;
    else
	//return DPL_RETURN_OS_ERROR(dpl_get_native_os_error());
	return -1;
#else
    dpl_assert( sem == (dpl_sem_t*)1 );
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_sem_post()
 */
dpl_status_t dpl_sem_post(dpl_sem_t *sem)
{
#if DPL_HAS_THREADS
    int result;
    
	dpl_v("Semaphore released by thread %s",dpl_thread_this()->obj_name);
    result = sem_post( sem->sem );

    if (result == 0)
	return DPL_SUCCESS;
    else
	//return DPL_RETURN_OS_ERROR(dpl_get_native_os_error());
	return -1;
#else
    dpl_assert( sem == (dpl_sem_t*) 1);
    return DPL_SUCCESS;
#endif
}

/*
 * dpl_sem_destroy()
 */
dpl_status_t dpl_sem_destroy(dpl_sem_t *sem)
{
#if DPL_HAS_THREADS
    int result;

    DPL_CHECK_STACK();
    //DPL_ASSERT_RETURN(sem, DPL_EINVAL);

    
	dpl_v("Semaphore destroyed by thread %s",dpl_thread_this()->obj_name);
#if defined(DPL_DARWINOS) && DPL_DARWINOS!=0
    result = sem_close( sem->sem );
#else
    result = sem_destroy( sem->sem );
#endif

    if (result == 0)
	return DPL_SUCCESS;
    else
	//return DPL_RETURN_OS_ERROR(dpl_get_native_os_error());
	return -1;
#else
    dpl_assert( sem == (dpl_sem_t*) 1 );
    return DPL_SUCCESS;
#endif
}

#endif	/* DPL_HAS_SEMAPHORE */

///////////////////////////////////////////////////////////////////////////////
#if defined(DPL_HAS_EVENT_OBJ) && DPL_HAS_EVENT_OBJ != 0

/*
 * dpl_event_create()
 */
dpl_status_t dpl_event_create(dpl_pool_t *pool, const char *name,
				    dpl_bool_t manual_reset, dpl_bool_t initial,
				    dpl_event_t **ptr_event)
{
    DPL_UNUSED_ARG(pool);
    dpl_assert(!"Not supported!");
    DPL_UNUSED_ARG(pool);
    DPL_UNUSED_ARG(name);
    DPL_UNUSED_ARG(manual_reset);
    DPL_UNUSED_ARG(initial);
    DPL_UNUSED_ARG(ptr_event);
    return DPL_EINVALIDOP;
}

/*
 * dpl_event_wait()
 */
dpl_status_t dpl_event_wait(dpl_event_t *event)
{
    DPL_UNUSED_ARG(event);
    return DPL_EINVALIDOP;
}

/*
 * dpl_event_trywait()
 */
dpl_status_t dpl_event_trywait(dpl_event_t *event)
{
    DPL_UNUSED_ARG(event);
    return DPL_EINVALIDOP;
}

/*
 * dpl_event_set()
 */
dpl_status_t dpl_event_set(dpl_event_t *event)
{
    DPL_UNUSED_ARG(event);
    return DPL_EINVALIDOP;
}

/*
 * dpl_event_pulse()
 */
dpl_status_t dpl_event_pulse(dpl_event_t *event)
{
    DPL_UNUSED_ARG(event);
    return DPL_EINVALIDOP;
}

/*
 * dpl_event_reset()
 */
dpl_status_t dpl_event_reset(dpl_event_t *event)
{
    DPL_UNUSED_ARG(event);
    return DPL_EINVALIDOP;
}

/*
 * dpl_event_destroy()
 */
dpl_status_t dpl_event_destroy(dpl_event_t *event)
{
    DPL_UNUSED_ARG(event);
    return DPL_EINVALIDOP;
}

#endif	/* DPL_HAS_EVENT_OBJ */

///////////////////////////////////////////////////////////////////////////////
#if defined(DPL_TERM_HAS_COLOR) && DPL_TERM_HAS_COLOR != 0
/*
 * Terminal
 */

/**
 * Set terminal color.
 */
dpl_status_t dpl_term_set_color(dpl_color_t color)
{
    /* put bright prefix to ansi_color */
    char ansi_color[12] = "\033[01;3";

    if (color & DPL_TERM_COLOR_BRIGHT) {
	color ^= DPL_TERM_COLOR_BRIGHT;
    } else {
	strcpy(ansi_color, "\033[00;3");
    }

    switch (color) {
    case 0:
	/* black color */
	strcat(ansi_color, "0m");
	break;
    case DPL_TERM_COLOR_R:
	/* red color */
	strcat(ansi_color, "1m");
	break;
    case DPL_TERM_COLOR_G:
	/* green color */
	strcat(ansi_color, "2m");
	break;
    case DPL_TERM_COLOR_B:
	/* blue color */
	strcat(ansi_color, "4m");
	break;
    case DPL_TERM_COLOR_R | DPL_TERM_COLOR_G:
	/* yellow color */
	strcat(ansi_color, "3m");
	break;
    case DPL_TERM_COLOR_R | DPL_TERM_COLOR_B:
	/* magenta color */
	strcat(ansi_color, "5m");
	break;
    case DPL_TERM_COLOR_G | DPL_TERM_COLOR_B:
	/* cyan color */
	strcat(ansi_color, "6m");
	break;
    case DPL_TERM_COLOR_R | DPL_TERM_COLOR_G | DPL_TERM_COLOR_B:
	/* white color */
	strcat(ansi_color, "7m");
	break;
    default:
	/* default console color */
	strcpy(ansi_color, "\033[00m");
	break;
    }

    fputs(ansi_color, stdout);

    return DPL_SUCCESS;
}

/**
 * Get current terminal foreground color.
 */
dpl_color_t dpl_term_get_color(void)
{
    return 0;
}

#endif	/* DPL_TERM_HAS_COLOR */

#if !defined(DPL_DARWINOS) || DPL_DARWINOS == 0
/*
 * dpl_run_app()
 */
int dpl_run_app(dpl_main_func_ptr main_func, int argc, char *argv[],
                       unsigned flags)
{
    return (*main_func)(argc, argv);
}
#endif

